package com.addplus.townmall.server.scheduled.scheduletask;

import com.addplus.townmall.server.api.mapper.town.*;
import com.addplus.townmall.server.api.model.town.TownOrder;
import com.addplus.townmall.server.api.utils.date.DateUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.List;

/**
 * 类名: IsSaleTimeoutTask
 *
 * @author zhangjiehang
 * @version V1.0
 * @date 2018/11/8 2:57 PM
 * @description 类描述: 修改订单状态定时器
 */
@Component
public class OrderStatusTask {

    private Logger logger = LoggerFactory.getLogger(OrderStatusTask.class);

    @Autowired
    CouponMapper couponMapper;

    @Autowired
    OrderItemsFightMapper orderItemsFightMapper;

    @Autowired
    TownOrderFightMapper townOrderFightMapper;
    @Autowired
    MemberIntegralMapper memberIntegralMapper;
    @Autowired
    TownOrderMapper townOrderMapper;

    /**
     * 方法描述：确认收货后超过7天取消售后
     *
     * @throws Exception
     * @author zhangjiehang
     * @date 2018/11/8 3:00 PM
     */
    @Scheduled(cron = "0 0 0 * * *")
    private void sevenDayTimeout() throws Exception {
        logger.info("确认收货后超过7天取消售后定时任务开始");
        QueryWrapper<TownOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_confirm", 1);
        queryWrapper.eq("is_sale", 0);
        queryWrapper.eq("is_delete", 0);
        List<TownOrder> townOrders = townOrderMapper.selectList(queryWrapper);
        if (townOrders == null || townOrders.isEmpty()) {
            logger.info("确认收货后超过7天取消售后，列表为空");
            return;
        } else {
            LocalDateTime localDateTimeNow = LocalDateTime.now();
            LocalDateTime localDateTimeNowFormat = LocalDateTime.of(localDateTimeNow.toLocalDate(), LocalTime.of(localDateTimeNow.getHour(), localDateTimeNow.getMinute(), 0));
            townOrders.forEach(item -> {
                LocalDateTime localConfirmTime = DateUtils.dateToLocalDateTimeSecondZero(item.getConfirmTime());
                System.out.println(ChronoUnit.DAYS.between(localConfirmTime, localDateTimeNowFormat));
                if ( ChronoUnit.DAYS.between(localConfirmTime, localDateTimeNowFormat)>=7) {
                    UpdateWrapper<TownOrder> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.eq("id", item.getId());
                    updateWrapper.set("is_sale", 1);
                    updateWrapper.set("gmt_modified", localDateTimeNow);
                    townOrderMapper.update(new TownOrder(), updateWrapper);
                }
            });
            logger.info("确认收货后超过7天取消售后定时任务完成");
        }
    }


    /**
     * 方法描述：订单未付款长时间未关闭的订单
     *
     * @throws Exception
     * @author zhangjiehang
     * @date 2018/11/8 3:00 PM
     */
    @Scheduled(cron = "0 0 0 * * *")
    private void processUnStart() throws Exception {
        logger.info("订单未付款长时间未关闭的订单定时任务开始");
        QueryWrapper<TownOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_status", 1);
        queryWrapper.eq("pay_status", 1);
        queryWrapper.eq("is_delete", 0);
        List<TownOrder> townOrders = townOrderMapper.selectList(queryWrapper);
        if (townOrders == null || townOrders.isEmpty()) {
            logger.info("订单未付款长时间未关闭的订单，列表为空");
            return;
        } else {
            LocalDateTime localDateTimeNow = LocalDateTime.now();
            LocalDateTime localDateTimeNowFormat = LocalDateTime.of(localDateTimeNow.toLocalDate(), LocalTime.of(localDateTimeNow.getHour(), localDateTimeNow.getMinute(), 0));
            townOrders.forEach(item -> {
                LocalDateTime localTimeOutDate = item.getTimeoutDate();
                if(localTimeOutDate!=null){
                    if (localDateTimeNowFormat.isEqual(localTimeOutDate) || localDateTimeNowFormat.isAfter(localTimeOutDate)) {
                        UpdateWrapper<TownOrder> updateWrapper = new UpdateWrapper<>();
                        updateWrapper.eq("id", item.getId());
                        updateWrapper.set("order_status", 6);
                        updateWrapper.set("close_reason","超时未付款，订单已关闭");
                        updateWrapper.set("close_date", localDateTimeNow);
                        updateWrapper.set("gmt_modified", localDateTimeNow);
                        townOrderMapper.update(new TownOrder(), updateWrapper);
                    }
                }
            });
            logger.info("订单未付款长时间未关闭的订单定时任务完成");
        }
    }


    /**
     * 方法描述：商家发货七天后自动收货
     *
     * @throws Exception
     * @author zhangjiehang
     * @date 2018/11/8 3:00 PM
     */
//  @Scheduled(cron = "0 */1 * * * ?")
    @Scheduled(cron = "0 0 0 * * ?")
    private void processConfirm() throws Exception {
        logger.info("商家发货20天后自动收货定时器任务开始");
        QueryWrapper<TownOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_confirm", 0);
        queryWrapper.eq("is_delete", 0);
        List<TownOrder> townOrders = townOrderMapper.selectList(queryWrapper);
        if (townOrders == null || townOrders.isEmpty()) {
            logger.info("商家发货七天后自动收货，列表为空");
            return;
        } else {
            LocalDateTime localDateTimeNow = LocalDateTime.now();
            LocalDateTime localDateTimeNowFormat = LocalDateTime.of(localDateTimeNow.toLocalDate(), LocalTime.of(localDateTimeNow.getHour(), localDateTimeNow.getMinute(), 0));
            townOrders.forEach(item -> {
                if(item.getShippingDate()!=null){
                    /*LocalDateTime localConfirmTime = DateUtils.dateToLocalDateTimeSecondZero(item.getConfirmTime());*/
                    LocalDateTime localConfirmTime = item.getShippingDate();
                    if ( ChronoUnit.DAYS.between(localConfirmTime, localDateTimeNowFormat)>20) {
                        UpdateWrapper<TownOrder> updateWrapper = new UpdateWrapper<>();
                        updateWrapper.eq("id", item.getId());
                        updateWrapper.eq("is_delete", 0);
                        updateWrapper.set("gmt_modified", localDateTimeNow);
                        updateWrapper.set("confirm_time", localDateTimeNow);
                        updateWrapper.set("finish_date", localDateTimeNow);
                        updateWrapper.set("is_confirm",1);
                        townOrderMapper.update(new TownOrder(), updateWrapper);
                    }
                }else{
                    logger.info("商家发货20天后自动收货，该订单发货日期为空");
                    return;
                }

            });
        }
        logger.info("商家发货20天后自动收货定时器任务结束");
    }


}
